package com.ones.mqtt.nano.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ones.common.core.exception.OnesServiceException;
import com.ones.common.core.util.OnesSpringContextHolder;
import com.ones.kit.extra.util.OnesHttpUtils;
import com.ones.mqtt.nano.autoconfigure.OnesNanoMqProperties;
import com.ones.mqtt.nano.model.OnesNanoMqPublishReq;
import com.ones.mqtt.nano.model.OnesNanoMqPublishRes;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;

/**
 * NanoMQ发布消息工具类
 *
 * @author Clark
 * @version 2024-11-21
 */
@Slf4j
@UtilityClass
public class OnesNanoMqUtils {

    private static OnesNanoMqProperties properties;
    static {
        try {
            properties = OnesSpringContextHolder.getBean(OnesNanoMqProperties.class);
        } catch (BeansException e) {
            log.error("******************* NanoMQ工具类装配失败 *******************");
            throw new OnesServiceException("MQTT服务异常，检测配置参数");
        }
        String url = StrUtil.builder().append(properties.getHost()).append(StrUtil.COLON).append(properties.getPort()).append(properties.getPath()).toString();
        OnesNanoMqUtils.init(url, properties.getClientId(), properties.getUsername(), properties.getPassword());
        log.warn("******************* NanoMQ工具类装配完成 *******************");
    }

    /**
     * 主机URL
     */
    private static String MQTT_URL;
    private static String CLIENT_ID;
    private static String USER;
    private static String PASS;

    /**
     * 初始化
     * @param mqttUrl
     * @param clientId
     * @param username
     * @param password
     */
    public void init(String mqttUrl, String clientId, String username, String password) {
        MQTT_URL = mqttUrl;
        CLIENT_ID = clientId;
        USER = username;
        PASS = password;
    }

    /**
     * http发布消息
     * Qos 默认值：0
     *
     * @param topic
     * @param payload
     */
    public boolean publish(String topic, String payload) {
        OnesNanoMqPublishReq dto = new OnesNanoMqPublishReq();
        dto.setClientId(CLIENT_ID);
        dto.setTopic(topic);
        dto.setPayload(payload);
        return publish(dto);
    }

    /**
     * http发布消息
     *
     * @param dto
     * @return
     */
    public boolean publish(OnesNanoMqPublishReq dto) {
        OnesNanoMqPublishRes res = publish4Res(dto);
        return res.isOk();
    }

    /**
     * http发布消息
     *
     * @param dto
     * @return OsMqttPublishRes
     */
    public OnesNanoMqPublishRes publish4Res(OnesNanoMqPublishReq dto) {
        // 设置客户端ID
        dto.setClientId(CLIENT_ID);
        String jsonStr = OnesHttpUtils.post4Auth(USER, PASS, MQTT_URL, JSONUtil.toJsonStr(dto));
        return JSONUtil.toBean(jsonStr, OnesNanoMqPublishRes.class);
    }
}